//
//  YWHomeInfoCell.m
//  YueshengToutiao
//
//  Created by jun peng on 2021/12/28.
//  Copyright © 2021 YW. All rights reserved.
//

#import "YWHomeInfoCell.h"
#import "YYText.h"
#import "YWConcernBtn.h"

#import "YWHomeIconCell.h"


#import "YWPhotoBrowserAnimator.h"

#define YWHomeIconCellID @"YWHomeIconCellID"


#define collectionLeadingTrailing 20

#define collectionInterval 0

//#define cellInterval 8

///防止小数所以减去1安全
//#define cellWidth ((Wi - 2*collectionLeadingTrailing - 2*cellInterval)/3 - 1)
//
//#define cellHeight cellWidth


#define oneImgCellInteval 0
#define multiImgCellInteval 8

#define oneImgCellWidth 175
#define oneImgCellHeight 117

///防止小数所以减去1安全
#define multiImgCellWidth (Wi - 2*collectionLeadingTrailing - 2*multiImgCellInteval)*1.0/3
#define multiImgCellHeight multiImgCellWidth





#define explainFont [UIFont systemFontOfSize:14]

@interface YWHomeInfoCell ()<UICollectionViewDelegate,UICollectionViewDataSource,YWPhotoBrowserAnimatorPresentedDelegate>

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

//@property (weak, nonatomic) IBOutlet YYLabel *cellLabel;
@property (weak, nonatomic) IBOutlet YYLabel *explainLabel;
@property (weak, nonatomic) IBOutlet UIButton *praiseBtn;
- (IBAction)praiseBtnClick:(UIButton *)sender;

//@property (weak, nonatomic) IBOutlet UIButton *seeBtn;
@property (weak, nonatomic) IBOutlet UIButton *shareBtn;
- (IBAction)shareBtnClick:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UIButton *unlockBtn;
- (IBAction)unlockBtnClick:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *unlockBtnConstraintHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *unlockBtnConstraintBottom;

@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *headIcon;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *expainLabelConstraintHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewConstraintHeight;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@property(nonatomic,strong)YWMeStatus *meStatus;


@property (weak, nonatomic) IBOutlet UICollectionView *iconCollectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iconCollectionViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iconCollectionViewWidthConstraint;
@property(nonatomic,strong)NSMutableArray *iconStatusArray;

@property (weak, nonatomic) IBOutlet YWConcernBtn *concernBtn;

- (IBAction)concernBtnClick:(UIButton *)sender;

//@property(nonatomic,strong)NSArray<NSString *> *picUrlArray;

//@property(nonatomic,strong)YWPhotoBrowserAnimator *animator; //这个发送通知给VC的时候才设置代理

@end

@implementation YWHomeInfoCell

//-(NSArray *)picUrlArray{
//    if (_picUrlArray == nil) {
//        _picUrlArray = [NSArray array];
//    }
//    return _picUrlArray;
//}

-(NSMutableArray *)iconStatusArray{
    
    if (_iconStatusArray == nil) {
        _iconStatusArray = [NSMutableArray array];
    }
    return _iconStatusArray;
}

-(YWMeStatus *)meStatus{
    //从本地加载meStatus
    _meStatus = [NSKeyedUnarchiver unarchiveObjectWithFile:YWMepath];
    
    return _meStatus;
    
}


+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    static NSString *ID = @"YWHomeInfoCell";
    YWHomeInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        // 从xib中加载cell
        cell = [[[NSBundle mainBundle] loadNibNamed:@"YWHomeInfoCell" owner:nil options:nil] lastObject];
    }
    return cell;
}



- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self.iconCollectionView registerNib:[UINib nibWithNibName:@"YWHomeIconCell" bundle:nil] forCellWithReuseIdentifier:YWHomeIconCellID];

    
    self.headIcon.layer.cornerRadius = 20;
    self.headIcon.userInteractionEnabled = YES;
    UITapGestureRecognizer *headIconTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headIconTap)];
    [self.headIcon addGestureRecognizer:headIconTap];
    
    
    self.unlockBtn.layer.cornerRadius = 6.0;
    
    //解释label
    self.explainLabel.numberOfLines = 2;  //设置2行显示
    self.explainLabel.preferredMaxLayoutWidth = Wi - 40;//设置最大的宽度
    
    
    //一开始默认是这样
    self.unlockBtn.hidden = YES;
    self.unlockBtnConstraintHeight.constant = 0;
    self.unlockBtnConstraintBottom.constant = 0;
    [self.unlockBtn setTitle:@"" forState:UIControlStateNormal];
    
    
}

-(void)setStatus:(YWGetNewsDataStatus *)status{
    
    _status = status;
    
    self.timeLabel.text = status.AddDateTime;
    
    self.nameLabel.text = status.Author;
    
    
    
    if ([status.AuthorImg isKindOfClass:[NSNull class]] || status.AuthorImg == nil) {
        status.AuthorImg = @"";
    }
    
    [self.headIcon sd_setImageWithURL:[NSURL URLWithString:status.AuthorImg] placeholderImage:[UIImage imageNamed:@"头像3"]];
    
    
    //栏目用的头像和名字是不一样的
    if (status.isClassify) {
        if ([status.LabelHeadImg isKindOfClass:[NSNull class]] || status.LabelHeadImg == nil) {
            status.LabelHeadImg = @"";
        }
        
        [self.headIcon sd_setImageWithURL:[NSURL URLWithString:status.LabelHeadImg] placeholderImage:[UIImage imageNamed:@"头像3"]];
        
        
        self.nameLabel.text = status.LabelName;
        
    }
    
    
    
//    [self.seeBtn setTitle:[NSString stringWithFormat:@"%@",status.Reading] forState:UIControlStateNormal];
    
    if (status.IsLike.integerValue == 1) {
        
        [self.praiseBtn setImage:[UIImage imageNamed:@"赞"] forState:UIControlStateNormal];
        
        [self.praiseBtn setTitleColor:mainColor forState:UIControlStateNormal];
        
        [self.praiseBtn setTitle:[NSString stringWithFormat:@"%@",status.Praise] forState:UIControlStateNormal];
    }
    else{
        
         [self.praiseBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        
        [self.praiseBtn setImage:[UIImage imageNamed:@"赞-未选中"] forState:UIControlStateNormal];
        
        [self.praiseBtn setTitle:[NSString stringWithFormat:@"点赞"] forState:UIControlStateNormal];
    }
    
    
    //现在暂时不需要解锁按钮了
    /*
    
    //登录了、且需要购买、且我还没购买 才需要显示解锁按钮 （或者未登录并且需要登录才能看才要显示）
    if (((status.ViewUser.integerValue == 3) && (status.IsBuy.integerValue == 0) && self.meStatus.isLogin) || (!self.meStatus.isLogin && (self.status.ViewUser.integerValue == 2))|| (!self.meStatus.isLogin && (self.status.ViewUser.integerValue == 3))){
        
        self.unlockBtn.hidden = NO;
        self.unlockBtnConstraintHeight.constant = 42;
        self.unlockBtnConstraintBottom.constant = 15;
        
        //防止后台返回空导致了奔溃
        if ([status.BuyWords isKindOfClass:[NSNull class]]) {
            status.BuyWords = @"暂无信息";
        }
        
//        if (self.meStatus.isLogin) {
//
//            [self.unlockBtn setTitle:status.BuyWords forState:UIControlStateNormal];
//        }
//        else{
//
//            [self.unlockBtn setTitle:@"请登录后查看" forState:UIControlStateNormal];
//        }

        [self.unlockBtn setTitle:status.BuyWords forState:UIControlStateNormal];
        
        //隐藏底部工具栏
        self.bottomView.hidden = YES;
        self.bottomViewConstraintHeight.constant = 0;
    }
    else{
         self.unlockBtn.hidden = YES;
         self.unlockBtnConstraintHeight.constant = 0;
         self.unlockBtnConstraintBottom.constant = 0;
         [self.unlockBtn setTitle:@"" forState:UIControlStateNormal];
        
        //显示底部工具栏
        self.bottomView.hidden = NO;
        self.bottomViewConstraintHeight.constant = 38;
    }
    
    */
    
    
        NSString *totalString = status.Title;
        
        //创建NSMutableAttributedString
//        NSMutableAttributedString *mastring = [[NSMutableAttributedString alloc] initWithString:totalString];
//
//        mastring.yy_lineSpacing = 8;
//        mastring.yy_font = [UIFont systemFontOfSize:16];
//
//        NSRange titleRange = [totalString rangeOfString:totalString];
//
//          [mastring yy_setTextHighlightRange:titleRange color:[UIColor blackColor] backgroundColor:[UIColor clearColor] tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
//               if ([self.delegate respondsToSelector:@selector(listCell:didClickContentWithDataStatus:)]) {
//                   [self.delegate listCell:self didClickContentWithDataStatus:self.status];
//               }
//
//            }];
//
//        self.cellLabel.attributedText = mastring;
        
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:8];
    
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:totalString attributes: @{NSForegroundColorAttributeName: YWColor(51, 51, 51),NSParagraphStyleAttributeName:paragraphStyle}];
    self.titleLabel.attributedText = string;
    
    
    
    NSString *totalString2 = status.Describe;
    if ([totalString2 containsString:@"\n"]) {
        totalString2 = [totalString2 stringByReplacingOccurrencesOfString:@"\n" withString:@""];

    }
    
    if (totalString2.length == 0) {
        self.expainLabelConstraintHeight.constant = 0;
    }
    else{
        self.expainLabelConstraintHeight.constant = 48;
    }
        
        //创建NSMutableAttributedString
        NSMutableAttributedString *mastring2 = [[NSMutableAttributedString alloc] initWithString:totalString2];
        
        mastring2.yy_lineSpacing = 8;
        mastring2.yy_font = explainFont;
        
        
        NSRange titleRange2 = [totalString2 rangeOfString:totalString2];
        
          [mastring2 yy_setTextHighlightRange:titleRange2 color:YWColor(105, 105, 105) backgroundColor:[UIColor clearColor] tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
               if ([self.delegate respondsToSelector:@selector(listCell:didClickContentWithDataStatus:)]) {
                          [self.delegate listCell:self didClickContentWithDataStatus:self.status];
                      }
              
            }];
        
        self.explainLabel.attributedText = mastring2;

//判断是不是第一个cell
    if (status.isFirstStatus) {
        UIImageView *bgView = [[UIImageView alloc] init];
        bgView.image = [UIImage yf_resizingWithImaName:@"firstCellBg"];
        self.backgroundView = bgView;
        self.backgroundColor = [UIColor clearColor];
    }
    else{
        self.backgroundView = nil;
        self.backgroundColor = [UIColor whiteColor];
    }
   
    

    //测试
//    if (status.ArrImg > 0) {
//
//        NSString *img = status.ArrImg[0];
//
//        status.ArrImg = @[img,img,img,img,img,img,img,img,img];
//    }
    
    //-----------------------------------------------------
    
    if (status.ArrImg.count>9) {
        status.ArrImg = [status.ArrImg subarrayWithRange:NSMakeRange(0, 9)];
    }
    
    self.iconStatusArray = [NSMutableArray arrayWithArray:status.ArrImg];
    
    
    if (self.iconStatusArray.count == 0) {   ///0
        
        self.iconCollectionViewWidthConstraint.constant = 0;
        self.iconCollectionViewHeightConstraint.constant = 0;
    }
    else if (self.iconStatusArray.count == 1){     ///1
        
        
        self.iconCollectionViewWidthConstraint.constant = oneImgCellWidth;
        self.iconCollectionViewHeightConstraint.constant = oneImgCellHeight;
    }
    else if (self.iconStatusArray.count == 4){     ///4
        
        self.iconCollectionViewWidthConstraint.constant = multiImgCellWidth *2 + multiImgCellInteval;
        self.iconCollectionViewHeightConstraint.constant = multiImgCellHeight *2 + multiImgCellInteval;
        
    }
    else if (self.iconStatusArray.count <= 3){     ///2 ~ 3
        
        self.iconCollectionViewWidthConstraint.constant = multiImgCellWidth *3 + multiImgCellInteval*2;
        self.iconCollectionViewHeightConstraint.constant = multiImgCellHeight;
        
    }
    else if (self.iconStatusArray.count <= 6){     ///5 ~ 6
        
        
        self.iconCollectionViewWidthConstraint.constant = multiImgCellWidth *3 + multiImgCellInteval*2;
        self.iconCollectionViewHeightConstraint.constant = multiImgCellHeight *2 + multiImgCellInteval;
    }
    else {   ///7 ~ 9
        
        self.iconCollectionViewWidthConstraint.constant = multiImgCellWidth *3 + multiImgCellInteval*2;
        self.iconCollectionViewHeightConstraint.constant = multiImgCellHeight *3 + multiImgCellInteval*2;
        
    }
    
    
    

    [self.iconCollectionView reloadData];
    
    
    if (status.IsFocus.intValue == 1) {
        self.concernBtn.isSelect = YES;
    }
    else{
        
        self.concernBtn.isSelect = NO;
    }
    
    
    if (status.isClassify == 1 || status.isTeacherList == 1) {
        self.concernBtn.hidden = YES;
    }
    else{
        
            self.concernBtn.hidden = NO;
        
    }
}

-(void)headIconTap{
    if ([self.delegate respondsToSelector:@selector(listCell:didClickHeadWithStatus:)]) {
        [self.delegate listCell:self didClickHeadWithStatus:self.status];
    }
}

- (IBAction)praiseBtnClick:(UIButton *)sender {
    
    if ([self.delegate respondsToSelector:@selector(listCell:didClickPraiseWithDataStatus:)]) {
        [self.delegate listCell:self didClickPraiseWithDataStatus:self.status];
    }
}


- (IBAction)shareBtnClick:(UIButton *)sender {
    
    if ([self.delegate respondsToSelector:@selector(listCell:didClickShareWithDataStatus:)]) {
        [self.delegate listCell:self didClickShareWithDataStatus:self.status];
    }
}
- (IBAction)unlockBtnClick:(UIButton *)sender {
    
    if ([self.delegate respondsToSelector:@selector(listCell:didClickUnlockBtnWithDataStatus:)]) {
        [self.delegate listCell:self didClickUnlockBtnWithDataStatus:self.status];
    }
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    
}

-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
    
}

- (IBAction)concernBtnClick:(UIButton *)sender {
    
   
    if ([self.delegate respondsToSelector:@selector(listCell:didConcernWithStatus:)]) {
        [self.delegate listCell:self didConcernWithStatus:self.status];
    }
    
    
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
     return self.iconStatusArray.count;
    
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    YWHomeIconCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:YWHomeIconCellID forIndexPath:indexPath];
    
               NSString *imageStr = self.iconStatusArray[indexPath.item];

               cell.imageStr = imageStr;
    
               return cell;
   
}

//定义每个UICollectionViewCell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.iconStatusArray.count == 1) {
        return CGSizeMake(oneImgCellWidth, oneImgCellHeight);
    }
    else{
        
        
       return CGSizeMake(multiImgCellWidth, multiImgCellHeight);
    }
    
}

//定义每个UICollectionView的内边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}


//设置水平间距,默认的垂直和水平间距都是0
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (self.iconStatusArray.count == 1) {
        return oneImgCellInteval;
    }
    else{
        
        
       return multiImgCellInteval;
    }
}

//设置垂直间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (self.iconStatusArray.count == 1) {
        return oneImgCellInteval;
    }
    else{
        
        
       return multiImgCellInteval;
    }
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    if ([self.delegate respondsToSelector:@selector(listCell:didClickImgWithImgIndexPath:imgStrArray:)]) {
//        [self.delegate listCell:self didClickImgWithImgIndexPath:indexPath imgStrArray:self.status.ArrImg];
//    }
    
    
    //我这里就不用代理了、用自制图片浏览器、改为用通知
    // 1.获取通知需要传递的参数
    NSDictionary *userInfo = @{ShowPhotoBrowserIndexKey:indexPath,ShowPhotoBrowserUrlsKey:self.iconStatusArray};
    
    // 2.发出通知
    [[NSNotificationCenter defaultCenter] postNotificationName:ShowPhotoBrowserNote object:self userInfo:userInfo];
}

-(CGRect)startRect:(NSIndexPath *)contentBeginIndexPath{
    
    YWHomeIconCell *cell = (YWHomeIconCell *)[self.iconCollectionView cellForItemAtIndexPath:contentBeginIndexPath];
    
    CGRect startRect = [self.iconCollectionView convertRect:cell.frame toView:[UIApplication sharedApplication].keyWindow];
    
    return startRect;
   
    
    
}

-(CGRect)endRect:(NSIndexPath *)contentBeginIndexPath{

    NSString *littleUrlString = self.iconStatusArray[contentBeginIndexPath.item];
    UIImage *littleImage = [[SDWebImageManager sharedManager].imageCache imageFromDiskCacheForKey:littleUrlString];
    CGFloat height = 0;
    if (littleImage == nil) { //还没缓存到littleImage、默认是正方形的frame
        // 3.计算imageView的frame
        CGFloat width = Wi;
        height = width;
        CGFloat y = 0;
        
        y = (He - height)*0.5;
      
        return CGRectMake(0, y, width, height);
    }
    else{
        
        // 3.计算imageView的frame
        CGFloat width = Wi;
        height = width / littleImage.size.width * littleImage.size.height;
        CGFloat y = 0;
        
        if (height > He) {
            y = 0;
        }
        else{
            y = (He - height)*0.5;
        }
      
        
        
          return CGRectMake(0, y, width, height);
      
      
    }
    
    

}


-(UIImageView *)imageView:(NSIndexPath *)contentBeginIndexPath{
    // 1.创建UIImageView对象
    UIImageView *imageView = [[UIImageView alloc] init];
    
//    imageView.backgroundColor = [UIColor whiteColor];
    
    // 2.获取该位置的image对象
    NSString *picURL = self.iconStatusArray[contentBeginIndexPath.item];
    
    UIImage *littleImage = [[SDWebImageManager sharedManager].imageCache imageFromDiskCacheForKey:picURL];
    
    // 3.设置imageView的属性
    imageView.image = littleImage;
    
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    
    return imageView;
}



@end
